package com.j2eefast.flowable.bpm.controller;

import com.j2eefast.common.core.business.annotaion.BussinessLog;
import com.j2eefast.common.core.enums.BusinessType;
import com.j2eefast.common.core.utils.*;
import com.j2eefast.flowable.bpm.entity.*;
import com.j2eefast.flowable.bpm.entity.output.FlowElementUserTaskEntity;
import com.j2eefast.flowable.bpm.service.BpmTaskFromService;
import com.j2eefast.flowable.bpm.service.IFlowableTaskService;
import com.j2eefast.flowable.bpm.utils.BpmConstant;
import com.j2eefast.flowable.bpm.utils.FlowableUtils;
import com.j2eefast.framework.annotation.RepeatSubmit;
import com.j2eefast.common.core.controller.BaseController;
import com.j2eefast.framework.sys.entity.ImputUserRoleEntity;
import com.j2eefast.framework.sys.entity.outentity.OutUserRoleEntity;
import com.j2eefast.framework.sys.service.SysUserService;
import com.j2eefast.framework.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.ui.ModelMap;

import java.util.*;

import org.springframework.web.bind.annotation.*;
import com.j2eefast.flowable.bpm.service.bpmCrmPurchaseService;

/**
 * 采购订单页面控制器
 *
 * @author yhli
 * @date 2020-06-28 13:40
 */
@Controller
@RequestMapping("/bpm/purchase")
public class bpmCrmPurchaseController extends BaseController {

    private String prefix = "modules/bpm/purchase";
    @Autowired
    private bpmCrmPurchaseService bpmCrmPurchaseService;
    /**
     * 必须注入实例关联表单服务
     */
    @Autowired
    private BpmTaskFromService bpmTaskFromService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private IFlowableTaskService flowableTaskService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    private HistoryService historyService;
    @RequiresPermissions("bpm:purchase:view")
    @GetMapping()
    public String purchase() {
        return prefix + "/purchase";
    }

    @RequestMapping("/list")
    @RequiresPermissions("bpm:purchase:list")
    @ResponseBody
    public ResponseData list(@RequestParam Map<String, Object> params, bpmCrmPurchaseEntity bpmCrmPurchaseEntity) {
        PageUtil page = bpmCrmPurchaseService.findPage(params, bpmCrmPurchaseEntity);
        return success(page);
    }

    //    @GetMapping("/add")
//    public String add(ModelMap mmap){
//         bpmCrmPurchaseEntity bpmCrmPurchase = new bpmCrmPurchaseEntity();
//          mmap.put("bpmCrmPurchase", bpmCrmPurchase);
//        return prefix + "/add";
//    }
    @GetMapping("/add/{taskId}/{id}")
    public String add(@PathVariable(value = "taskId", required = true) String taskId, @PathVariable(value = "id", required = true) Long id, ModelMap mmp) {
        BpmModelEntity data = flowableTaskService.getVariables(taskId);
        BpmTaskEntity entity = flowableTaskService.getTasksByTaskId(taskId);
//        UserTask userTask = flowableTaskService.newFlowable(taskId);
        List<OutUserRoleEntity> userInfos = getFlowableUserInfo(taskId,entity.getProcessInstanceId());
        //通过页面传入的表单ID查询表单关联信息
        BpmTaskFromEntity bpmTaskFrom = bpmTaskFromService.getTaskFromById(id);
        mmp.put("saleCode", data.getSaleCode());
        mmp.put("saleOrderNumber", OrderCodeFactory.generateCGAgain(UserUtils.getUserId()));
        mmp.put("bpmTaskFrom", bpmTaskFrom);
        mmp.put("taskEntity", entity);
        mmp.put("user", UserUtils.getUserInfo());
        mmp.put("userInfo",userInfos);
        return prefix + "/add";
    }

    /**
     * 定义关联表单申请表单URL对应此处
     */
    @GetMapping("/add/{id}")
    public String add(@PathVariable("id") Long id, ModelMap mmp) {
        //通过页面传入的表单ID查询表单关联信息
        BpmTaskFromEntity bpmTaskFrom = bpmTaskFromService.getTaskFromById(id);
        mmp.put("bpmTaskFrom", bpmTaskFrom);
        mmp.put("user", UserUtils.getUserInfo());
        return prefix + "/add";
    }

    /**
     * 新增
     */
    @RepeatSubmit
    @RequiresPermissions("bpm:purchase:add")
    @BussinessLog(title = "采购订单", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData addbpmCrmPurchase(@Validated bpmCrmPurchaseEntity bpmCrmPurchase, @Validated CompleteTaskEntity params) {
        //校验参数
        //ValidatorUtil.validateEntity(bpmCrmPurchase);
        ResponseData result = bpmCrmPurchaseService.savebpmCrmPurchase(bpmCrmPurchase) ? success() : error("新增失败!");
        Map<String, Object> mp = new HashMap<>();
        mp.put(BpmConstant.IS_WAI, params.getIsWai());
        params.setIsWai(params.getIsWai());
        flowableTaskService.complete(params);
        return result;
    }

    /**
     * 修改
     */
    @RequiresPermissions("bpm:purchase:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        bpmCrmPurchaseEntity bpmCrmPurchase = bpmCrmPurchaseService.getbpmCrmPurchaseById(id);
        mmap.put("bpmCrmPurchase", bpmCrmPurchase);
        return prefix + "/edit";
    }

    /**
     * 修改
     */
    @RequiresPermissions("bpm:purchase:view")
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") String id, ModelMap mmap) {
        bpmCrmPurchaseEntity bpmCrmPurchase = bpmCrmPurchaseService.getbpmCrmPurchaseById(id);
        mmap.put("bpmCrmPurchase", bpmCrmPurchase);
        return prefix + "/view";
    }

    /**
     * 审批1（销售员）
     */
    @RequiresPermissions("bpm:purchase:view1")
    @GetMapping("/view1/{id}")
    public String view1(@PathVariable("id") String id, ModelMap mmap) {
        bpmCrmPurchaseEntity bpmCrmPurchase = bpmCrmPurchaseService.getbpmCrmPurchaseById(id);
        mmap.put("bpmCrmPurchase", bpmCrmPurchase);
        return prefix + "/view1";
    }

    /**
     * 审批2（采购经理）
     */
    @RequiresPermissions("bpm:purchase:view2")
    @GetMapping("/view2/{id}")
    public String view2(@PathVariable("id") String id, ModelMap mmap) {
        bpmCrmPurchaseEntity bpmCrmPurchase = bpmCrmPurchaseService.getbpmCrmPurchaseById(id);
        mmap.put("bpmCrmPurchase", bpmCrmPurchase);
        return prefix + "/view2";
    }

    /**
     * 审批3（采购专员）
     */
    @RequiresPermissions("bpm:purchase:view3")
    @GetMapping("/view3/{id}")
    public String view3(@PathVariable("id") String id, ModelMap mmap) {
        bpmCrmPurchaseEntity bpmCrmPurchase = bpmCrmPurchaseService.getbpmCrmPurchaseById(id);
        mmap.put("bpmCrmPurchase", bpmCrmPurchase);
        return prefix + "/view3";
    }

    /**
     * 审批4（库存专员）
     */
    @RequiresPermissions("bpm:purchase:view4")
    @GetMapping("/view4/{id}")
    public String view4(@PathVariable("id") String id, ModelMap mmap) {
        bpmCrmPurchaseEntity bpmCrmPurchase = bpmCrmPurchaseService.getbpmCrmPurchaseById(id);
        mmap.put("bpmCrmPurchase", bpmCrmPurchase);
        return prefix + "/view4";
    }

    /**
     * 审批5（出纳）
     */
    @RequiresPermissions("bpm:purchase:view5")
    @GetMapping("/view5/{id}")
    public String view5(@PathVariable("id") String id, ModelMap mmap) {
        bpmCrmPurchaseEntity bpmCrmPurchase = bpmCrmPurchaseService.getbpmCrmPurchaseById(id);
        mmap.put("bpmCrmPurchase", bpmCrmPurchase);
        return prefix + "/view5";
    }

    /**
     * 修改保存采购订单
     */
    @RepeatSubmit
    @RequiresPermissions("bpm:purchase:edit")
    @BussinessLog(title = "采购订单", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData editbpmCrmPurchase(bpmCrmPurchaseEntity bpmCrmPurchase) {
        ValidatorUtil.validateEntity(bpmCrmPurchase);
        return bpmCrmPurchaseService.updatebpmCrmPurchaseById(bpmCrmPurchase) ? success() : error("修改失败!");
    }

    /**
     * 删除
     */
    @RepeatSubmit
    @BussinessLog(title = "采购订单", businessType = BusinessType.DELETE)
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @RequiresPermissions("bpm:purchase:del")
    @ResponseBody
    public ResponseData del(String[] ids) {
        return bpmCrmPurchaseService.deletebpmCrmPurchaseByIds(ids) ? success() : error("删除失败!");
    }

    /**
     * 获取用户信息
     * @param taskId
     * @return
     */
    @GetMapping("/selctUsers/{taskId}/{processInstanceId}")
    public  List<OutUserRoleEntity> getFlowableUserInfo(@PathVariable(value = "taskId", required = true) String taskId, @PathVariable(value = "processInstanceId", required = true) String processInstanceId){
       FlowElementUserTaskEntity userTask= flowableTaskService.nextFlowNode(taskId);
        if (!userTask.getIsEndvent()) {
            // 获取下一节点
//            List<HistoricTaskInstance> entity3=  historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();
//            List<HistoricTaskInstance> entity4=  historyService.createHistoricTaskInstanceQuery().taskDefinitionKey(key).list();
//            HistoricTaskInstance entity2=  historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).taskDefinitionKey(key).singleResult();
//            Task entity1 = taskService.createTaskQuery().processInstanceId(processInstanceId).taskDefinitionKey(key).singleResult();
//            UserTask userTask = flowableTaskService.newFlowable(entity4.get(0).getId());
            if(userTask.getCandidateGroups()!=null && userTask.getCandidateGroups().size()>0){
                ImputUserRoleEntity entity = new ImputUserRoleEntity();
                entity.setIds(FlowableUtils.stringConvLong(userTask.getCandidateGroups()));
                return sysUserService.getFlowableUserInfoByRole(entity);
            }else if(userTask.getCandidateUsers()!=null && userTask.getCandidateUsers().size()>0){
                ImputUserRoleEntity entity = new ImputUserRoleEntity();
                entity.setIds(FlowableUtils.stringConvLong(userTask.getCandidateUsers()));
                return sysUserService.getFlowableUserInfoByUserIds(entity);
            }else if(userTask.getAssignee()!=null && userTask.getAssignee().length()>0){
                ImputUserRoleEntity entity = new ImputUserRoleEntity();
                List<String> ids = new ArrayList<>();
                ids.add(userTask.getAssignee());
                entity.setIds(FlowableUtils.stringConvLong(ids));
                return sysUserService.getFlowableUserInfoByUserIds(entity);
            }
        }

        return null;
    }
}
